import React, { useEffect, useState } from "react";
import Cascader from "../../../Cascader";
import type { FieldBaseType } from "../../type";

type CascaderOptions = Array<{
  label: string;
  value: string | number;
  children?: CascaderOptions;
}>;

export default function CascaderField({
  field,
  isValid,
  onChange,
}: {
  field: FieldBaseType<Array<string | number>>;
  isValid: boolean;
  onChange: (v: Array<string | number>) => void;
}) {
  const { value, defaultValue, disabled, options, placeholder, meta } = field;

  const [innerOpts, setOpts] = useState<CascaderOptions>();

  useEffect(() => {
    if (!options) return;
    if (typeof options == "function") {
      options().then((r) => setOpts(r));
    } else {
      setOpts(options);
    }
  }, [options]);

  return (
    <Cascader
      disabled={disabled}
      placeholder={placeholder}
      style={isValid ? undefined : { border: "1px solid #c55252" }}
      value={value ?? defaultValue ?? []}
      options={innerOpts}
      allowClear={meta?.allowClear}
      changeOnSelect={meta?.changeOnSelect}
      onChange={onChange}
      notFoundContent={meta?.notFoundContent}
    />
  );
}
